<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 仪表板</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 仪表板页面 -->
            <div id="dashboard" class="content-page active">
                <div class="page-header">
                    <div class="header-content">
                        <h2>系统仪表板</h2>
                        <p>欢迎使用图书馆管理系统 - 实时监控面板</p>
                    </div>
                    <div class="dashboard-actions">
                        <button class="btn btn-primary" onclick="window.open('statistics.html', '_blank')">
                            <i class="fas fa-chart-bar"></i>
                            查看详细统计
                        </button>
                        <button class="btn btn-secondary" onclick="loadDashboard()">
                            <i class="fas fa-sync-alt"></i>
                            刷新数据
                        </button>
                    </div>
                </div>
                <div class="dashboard-stats">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="totalUsers">0</h3>
                            <p>总用户数</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-book"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="totalBooks">0</h3>
                            <p>总图书数</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-exchange-alt"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="totalBorrows">0</h3>
                            <p>总借阅数</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="overdueBorrows">0</h3>
                            <p>逾期借阅</p>
                        </div>
                    </div>
                </div>
                <div class="dashboard-charts">
                    <div class="chart-container">
                        <h3>最近借阅趋势</h3>
                        <canvas id="borrowChart"></canvas>
                    </div>
                    <div class="chart-container">
                        <h3>图书分类统计</h3>
                        <canvas id="categoryChart"></canvas>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 通知弹窗 -->
    <div id="notificationModal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3>系统通知</h3>
                <button class="modal-close" onclick="closeNotificationModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div id="notificationList">
                </div>
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // API基础配置
        const API_BASE_URL = 'http://118.31.223.190:8080';

        // 通用API请求函数
        class ApiClient {
            constructor() {
                this.baseURL = API_BASE_URL;
            }

            async request(url, options = {}) {
                const isForm = options && options.body instanceof FormData;
                const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
                const config = { headers, ...options };

                try {
                    const response = await fetch(`${this.baseURL}${url}`, config);
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    return data;
                } catch (error) {
                    console.error('API请求失败:', error);
                    throw error;
                }
            }

            async get(url, params = {}) {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = queryString ? `${url}?${queryString}` : url;
                return this.request(fullUrl, { method: 'GET' });
            }

            async post(url, data = {}) {
                if (data instanceof FormData) {
                    return this.request(url, { method: 'POST', body: data });
                }
                return this.request(url, { method: 'POST', body: JSON.stringify(data) });
            }

            async put(url, data = {}) {
                return this.request(url, {
                    method: 'PUT',
                    body: JSON.stringify(data)
                });
            }

            async delete(url) {
                return this.request(url, { method: 'DELETE' });
            }
        }

        // 创建API客户端实例
        const api = new ApiClient();

        // 用户管理API
        const UserAPI = {
            // 分页查询用户
            pageUsers: (page = 1, size = 10, keyword = '') => 
                api.get('/api/users/page', { page, size, keyword })
        };

        // 图书管理API
        const BookAPI = {
            // 分页查询图书
            pageBooks: (page = 1, size = 10, keyword = '', categoryName = '') => 
                api.get('/api/books/page', { page, size, keyword, categoryName })
        };

        // 借阅管理API
        const BorrowAPI = {
            // 分页查询借阅记录
            pageBorrows: (page = 1, size = 10, userId = '', status = '', keyword = '') => {
                const params = { page, size };
                if (userId !== '' && userId !== null && userId !== undefined) params.userId = userId;
                if (status !== '' && status !== null && status !== undefined) params.status = status;
                if (keyword !== '' && keyword !== null && keyword !== undefined) params.keyword = keyword;
                return api.get('/api/borrows/page', params);
            },
            
            // 获取逾期借阅
            getOverdueBorrows: (page = 1, size = 10) => 
                api.get('/api/borrows/overdue', { page, size })
        };

        // 图书分类管理API
        const BookCategoryAPI = {
            // 获取所有分类
            getAllCategories: () => api.get('/api/book-categories')
        };

        // 工具函数
        const Utils = {
            // 显示加载状态
            showLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.add('active');
                }
            },

            // 隐藏加载状态
            hideLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.remove('active');
                }
            },

            // 显示消息提示
            showMessage: (message, type = 'info', duration = 3000) => {
                const messageContainer = document.getElementById('messageContainer');
                if (!messageContainer) return;

                const messageEl = document.createElement('div');
                messageEl.className = `message ${type}`;
                
                const iconMap = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle'
                };

                messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                messageContainer.appendChild(messageEl);

                // 自动移除消息
                setTimeout(() => {
                    if (messageEl.parentElement) {
                        messageEl.remove();
                    }
                }, duration);
            }
        };

        // 全局变量
        let currentUser = null;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
        });

        // 初始化应用
        function initializeApp() {
            // 使用通用权限检查
            if (!initializePagePermission()) {
                return;
            }
            
            currentUser = authManager.getCurrentUser();
            
            // 生成动态菜单
            generateSidebarMenu();
            
            // 更新用户信息
            document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
            
            // 应用权限控制
            authManager.applyPermissionControl();
            
            // 加载仪表板数据
            loadDashboard();
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 检查登录状态（保留兼容性）
        function checkLoginStatus() {
            return authManager.isLoggedIn();
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            authManager.logout();
            Utils.showMessage('已退出登录', 'info');
        }

        // 显示通知
        function showNotifications() {
            // 实现通知显示逻辑
            Utils.showMessage('通知功能开发中', 'info');
        }

        // 关闭通知模态框
        function closeNotificationModal() {
            document.getElementById('notificationModal').classList.remove('active');
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载仪表板数据
        async function loadDashboard() {
            try {
                Utils.showLoading();
                
                // 并行加载统计数据
                const [usersResponse, booksResponse, borrowsResponse, overdueResponse] = await Promise.all([
                    UserAPI.pageUsers(1, 1),
                    BookAPI.pageBooks(1, 1),
                    BorrowAPI.pageBorrows(1, 1),
                    BorrowAPI.getOverdueBorrows(1, 1)
                ]);
                
                // 更新统计数据
                document.getElementById('totalUsers').textContent = usersResponse.data?.total || 0;
                document.getElementById('totalBooks').textContent = booksResponse.data?.total || 0;
                document.getElementById('totalBorrows').textContent = borrowsResponse.data?.total || 0;
                document.getElementById('overdueBorrows').textContent = overdueResponse.data?.total || 0;
                
                // 确保 Chart.js 可用后再加载图表
                await ensureChartJsLoaded();
                loadCharts();
                
            } catch (error) {
                Utils.showMessage('加载仪表板数据失败', 'error');
                console.error('Dashboard load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 加载图表数据
        async function loadCharts() {
            try {
                if (typeof Chart === 'undefined') return; // 双重保护
                // 加载借阅趋势图
                const borrowsResponse = await BorrowAPI.pageBorrows(1, 100);
                const borrowsData = borrowsResponse.data?.records || [];
                
                // 按日期分组统计
                const borrowsByDate = {};
                borrowsData.forEach(borrow => {
                    const date = new Date(borrow.borrowDate).toLocaleDateString();
                    borrowsByDate[date] = (borrowsByDate[date] || 0) + 1;
                });
                
                const dates = Object.keys(borrowsByDate).sort();
                const counts = dates.map(date => borrowsByDate[date]);
                
                // 创建借阅趋势图
                const borrowCtx = document.getElementById('borrowChart');
                if (borrowCtx) {
                    new Chart(borrowCtx, {
                        type: 'line',
                        data: {
                            labels: dates,
                            datasets: [{
                                label: '借阅数量',
                                data: counts,
                                borderColor: '#667eea',
                                backgroundColor: 'rgba(102, 126, 234, 0.1)',
                                tension: 0.4
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    display: false
                                }
                            }
                        }
                    });
                }
                
                // 直接使用统计API获取分类数据
                const categoryStatsResponse = await fetch('/api/statistics/category-stats');
                const categoryStatsData = await categoryStatsResponse.json();
                const categoryStats = categoryStatsData.data || [];

                console.log('分类统计数据:', categoryStats);

                // 过滤掉图书数量为0的分类
                const filteredCategoryStats = categoryStats.filter(stat => stat.value > 0);

                console.log('过滤后的分类数据:', filteredCategoryStats);

                // 创建分类统计图
                const categoryCtx = document.getElementById('categoryChart');
                if (categoryCtx) {
                    new Chart(categoryCtx, {
                        type: 'doughnut',
                        data: {
                            labels: filteredCategoryStats.map(stat => stat.label),
                            datasets: [{
                                data: filteredCategoryStats.map(stat => stat.value),
                                backgroundColor: [
                                    '#667eea',
                                    '#f093fb',
                                    '#4facfe',
                                    '#43e97b',
                                    '#ffc107',
                                    '#dc3545',
                                    '#28a745',
                                    '#17a2b8',
                                    '#6f42c1',
                                    '#fd7e14',
                                    '#20c997',
                                    '#e83e8c',
                                    '#6c757d',
                                    '#007bff',
                                    '#28a745'
                                ]
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'bottom',
                                    labels: {
                                        usePointStyle: true,
                                        padding: 20
                                    }
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            const label = context.label || '';
                                            const value = context.parsed;
                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                            const percentage = ((value / total) * 100).toFixed(1);
                                            return `${label}: ${value}本 (${percentage}%)`;
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
                
            } catch (error) {
                console.error('Charts load error:', error);
            }
        }

        // 动态加载 Chart.js（多 CDN 兜底）
        async function ensureChartJsLoaded() {
            if (typeof Chart !== 'undefined') return true;
            const urls = [
                'https://cdn.jsdelivr.net/npm/chart.js',
                'https://unpkg.com/chart.js@latest/dist/chart.umd.js',
                'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js'
            ];
            for (const url of urls) {
                try {
                    await loadScript(url, 8000);
                    if (typeof Chart !== 'undefined') return true;
                } catch (_) {
                    // try next
                }
            }
            console.warn('Chart.js failed to load from all CDNs. Charts will be skipped.');
            return false;
        }

        function loadScript(src, timeoutMs = 10000) {
            return new Promise((resolve, reject) => {
                const s = document.createElement('script');
                s.src = src;
                s.async = true;
                let done = false;
                const cleanup = () => {
                    s.onload = null;
                    s.onerror = null;
                };
                s.onload = () => { if (!done) { done = true; cleanup(); resolve(); } };
                s.onerror = () => { if (!done) { done = true; cleanup(); reject(new Error('load error')); } };
                document.head.appendChild(s);
                setTimeout(() => { if (!done) { done = true; cleanup(); reject(new Error('timeout')); } }, timeoutMs);
            });
        }
    </script>
</body>
</html>
